const Route = require('./Route')
const Layer = require('./layer')
// 路由系统
function Router() {
  this.stack = []
}

Router.prototype.route = function(path) {
  let route = new Route()
  // 如果 layer 的路径匹配到了给交给 route 来处理
  let layer = new Layer(path, route.dispatch.bind(route))
  // 把 route 放到 layer 上
  layer.route = route
  // 把 layer 放到数组中
  this.stack.push(layer)
  return route
}

Router.prototype.get = function(path, handlers) {
  let route = this.route(path)
  // 把 handler 传递给 route 自身去处理
  route.get(handlers)
}

// 请求到来时处理函数
Router.prototype.handle = function(req, res, out) {
  let { pathname } = req.url
  let idx = 0
  let next = () => {
    // 无法匹配则返回
    if (idx >= this.stack.length) {
      return out()
    }
    let layer = this.stack[idx++]
    if (layer.match(pathname)) {
      // 判断当前的 layer 是否匹配到当前的请求路径
      // handle_request()  => route.dispatch.bind(route)
      // next 是外层的下一层
      layer.handle_request(req, res, next)
    } else {
      next()
    }
  }
  next()
}

module.exports = Router